import { formatMessage } from 'umi/locale';
import { menu } from '../defaultSettings';

// 配置路由转为菜单
export function formatter(data, parentName) {
  if (!data) {
    return undefined;
  }
  return data
    .map(item => {
      if (!item.name || !item.path) {
        return null;
      }

      let locale = 'menu';
      if (parentName && parentName !== '/') {
        locale = `${parentName}.${item.name}`;
      } else {
        locale = `menu.${item.name}`;
      }
      // disableLocale：禁用菜单国际化
      const name = menu.disableLocal ? item.name : formatMessage({ id: locale, defaultMessage: item.name });
      const result = {
        ...item,
        name,
        locale,
        authority: item.authority,
      };
      if (item.routes) {
        const children = formatter(item.routes, locale);
        // Reduce memory usage
        result.children = children;
      }
      delete result.routes;
      return result;
    })
    .filter(item => item);
};

// 根据权限过滤菜单
const filterMenuData = (menuData, authority) => {
  if (!menuData || !authority) {
    return [];
  }
  return menuData
    .map(item => {
      if (authority.indexOf(item.authority) < 0) {
        return null;
      } else {
        const result = {
          ...item,
        };
        if (item.children && item.children.length > 0) {
          const children = filterMenuData(item.children, authority);
          if (children && children.length > 0) {
            result.children = children;
          } else {
            delete result.children;
          }
        }
        return result;
      }
    })
    .filter(item => item);
};

// 扁平化的菜单Mao，便于生成面包屑
const getBreadcrumbNameMap = menuData => {
  if (!menuData) {
    return [];
  }
  const routerMap = [];

  const flattenMenuData = data => {
    data.forEach(menuItem => {
      if (menuItem.children) {
        flattenMenuData(menuItem.children);
      }
      routerMap.push(menuItem);
    });
  };
  flattenMenuData(menuData);
  return routerMap;
};

export default {
  namespace: 'menu',

  state: {
    menuData: [],
    routerData: [],
    breadcrumbNameMap: [],
  },

  effects: {
    *getMenuData({ payload }, { call, put }) {
      const { routes, authority } = payload;
      // int转为string
      let authorityStr = authority ? authority.map(item => item + '') : authority;
      const originalMenuData = formatter(routes);
      const menuData = filterMenuData(originalMenuData, authorityStr);
      const breadcrumbNameMap = getBreadcrumbNameMap(originalMenuData);
      yield put({
        type: 'save',
        payload: { menuData, routerData: routes, breadcrumbNameMap, },
      });
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};